<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务编号/名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务编号/名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单名称/编号" prop="workOrderName">
        <el-input
          v-model="queryParams.workOrderName"
          placeholder="请输入工单名称/编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选择工序" prop="process">
        <el-select v-model="queryParams.process" placeholder="请选择工序" clearable size="small">
          <el-option label="工序一" value="1" />
          <el-option label="工序二" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="未开始" value="0" />
          <el-option label="已派工" value="1" />
          <el-option label="进行中" value="2" />
          <el-option label="已完成" value="3" />
          <el-option label="已暂停" value="4" />
          <el-option label="待质检" value="5" />
        </el-select>
      </el-form-item>
      <template v-if="showMore">
        <el-form-item label="计划开始时间" prop="planStartTime">
          <el-date-picker
            v-model="queryParams.planStartTime"
            type="date"
            placeholder="选择计划开始时间"
            size="small">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planEndTime">
          <el-date-picker
            v-model="queryParams.planEndTime"
            type="date"
            placeholder="选择计划结束时间"
            size="small">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际开始时间" prop="actualStartTime">
          <el-date-picker
            v-model="queryParams.actualStartTime"
            type="date"
            placeholder="选择实际开始时间"
            size="small">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际结束时间" prop="actualEndTime">
          <el-date-picker
            v-model="queryParams.actualEndTime"
            type="date"
            placeholder="选择实际结束时间"
            size="small">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="选择工艺流程" prop="processFlow">
          <el-select v-model="queryParams.processFlow" placeholder="请选择工艺流程" clearable size="small">
            <el-option label="工艺流程一" value="1" />
            <el-option label="工艺流程二" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择站点" prop="station">
          <el-select v-model="queryParams.station" placeholder="请选择站点" clearable size="small">
            <el-option label="站点一" value="1" />
            <el-option label="站点二" value="2" />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="text" @click="toggleShowMore">{{ showMore ? '收起' : '更多' }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleDispatch"
        >派工</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleReport"
        >报工</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" type="index" width="50" align="center" fixed="left" />
      <el-table-column label="任务编号" align="center" prop="taskCode" width="150" fixed="left">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleTaskDetail(scope.row)"
            style="color: #409EFF; font-weight: bold;"
          >
            {{ scope.row.taskCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="车间名称" align="center" prop="workshopName" width="120" />
      <el-table-column label="工单编号" align="center" prop="workOrderCode" width="150" />
      <el-table-column label="工单名称" align="center" prop="workOrderName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="工艺流程" align="center" prop="operationalName" width="120" />
      <el-table-column label="工序名称" align="center" prop="taskName" width="120" />
      <el-table-column label="工序编号" align="center" prop="processCode" width="120" />
      <el-table-column label="任务颜色" align="center" prop="color" width="100">
        <template slot-scope="scope">
          <el-color-picker v-model="scope.row.color" size="mini"></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column label="计划数量" align="center" prop="planQuantity" width="100" />
      <el-table-column label="实际生产" align="center" prop="actualProduction" width="100" />
      <el-table-column label="计划开工时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.planStartTime) }}
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.planEndTime) }}
        </template>
      </el-table-column>
      <el-table-column label="计划生产时长" align="center" prop="plannedDuration" width="150" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" width="100" fixed="right" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.status === '0'"
                @click="handleAction(scope.row, 'dispatch')"
            >派工</el-button>
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.status === '1'"
                @click="handleAction(scope.row, 'start')"
            >开工</el-button>
             <el-button
                size="mini"
                type="text"
                v-if="scope.row.status === '1' || scope.row.status === '2'"
                @click="handleAction(scope.row, 'close')"
            >关闭</el-button>
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.status === '2'"
                @click="handleAction(scope.row, 'report')"
            >报工</el-button>
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.status === '2'"
                @click="handleAction(scope.row, 'complete')"
            >完成</el-button>
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.status === '3' || scope.row.status === '4' || scope.row.status === '5'"
                @click="handleAction(scope.row, 'restart')"
            >重启</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listTask } from "@/api/sc/task";
import { startWorkOrderTask, restartWorkOrderTask } from "@/api/sc/workOrderTask"; // 添加工序任务开工和重启API引用
import { formatDate } from "@/utils/index";

export default {
  name: "ScTask",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 显示更多搜索
      showMore: false,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 选中数组
      selection: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: undefined,
        workOrderName: undefined,
        process: undefined,
        status: undefined,
        planStartTime: undefined,
        planEndTime: undefined,
        actualStartTime: undefined,
        actualEndTime: undefined,
        processFlow: undefined,
        station: undefined
      },
       statusOptions: [
        { dictValue: "0", dictLabel: "未开始" },
        { dictValue: "1", dictLabel: "已派工" },
        { dictValue: "2", dictLabel: "进行中" },
        { dictValue: "3", dictLabel: "已完成" },
        { dictValue: "4", dictLabel: "已暂停" },
        { dictValue: "5", dictLabel: "待质检" },
      ],
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/task' || to.name === 'ScTask') {
        console.log('生产任务页面路由变化，刷新数据');
        this.getList();
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('生产任务查询参数变化，刷新数据');
          this.getList();
        }
      },
      deep: true
    }
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      const status = this.statusOptions.find(item => item.dictValue === row.status);
      return status ? status.dictLabel : "";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    /** 派工按钮操作 */
    handleDispatch() {
      if (this.selection.length === 0) {
        this.$modal.msgWarning("请选择要派工的任务");
        return;
      }
       if (this.selection.length > 1) {
         this.$modal.msgWarning("一次只能对一个任务进行派工");
         return;
       }
       const taskId = this.selection[0].workOrderTaskId;
       this.$router.push({ path: '/sc/task/dispatch', query: { id: taskId, t: new Date().getTime() } });
    },
    /** 报工按钮操作 */
    handleReport() {
      if (this.selection.length === 0) {
        this.$modal.msgWarning("请选择要报工的任务");
        return;
      }
      if (this.selection.length > 1) {
        this.$modal.msgWarning("一次只能对一个任务进行报工");
        return;
      }
      
      const row = this.selection[0];
      // 跳转到报工页面
      this.$router.push({
        path: '/sc/Signning',
        query: {
          taskId: row.workOrderTaskId,
          orderNo: row.workOrderCode,
          processName: row.taskName
        }
      });
    },
    /** 关闭按钮操作 */
    handleClose() {
      if (this.selection.length === 0) {
        this.$modal.msgWarning("请选择要关闭的任务");
        return;
      }
      const taskIds = this.selection.map(item => item.workOrderTaskId);
      this.$modal.confirm('确认要关闭选中的工序任务吗？').then(() => {
        // 这里应该调用批量关闭任务的API
        // 示例: closeWorkOrderTasks(taskIds)
        this.$message.success("任务关闭成功");
        this.getList(); // 刷新数据
      }).catch(() => {});
    },
    /** 切换更多搜索 */
    toggleShowMore() {
      this.showMore = !this.showMore;
    },
    /** 表格行内操作 */
    handleAction(row, action) {
        if (action === 'dispatch') {
             this.$router.push({ path: '/sc/task/dispatch', query: { id: row.workOrderTaskId, t: new Date().getTime() } });
        } else if (action === 'start') {
            this.startTask(row);
        } else if (action === 'report') {
            // 跳转到报工页面
            this.$router.push({
              path: '/sc/Signning',
              query: {
                taskId: row.workOrderTaskId,
                orderNo: row.workOrderCode,
                processName: row.taskName
              }
            });
        } else if (action === 'close') {
            // 关闭任务操作
            this.$modal.confirm('确认要关闭此工序任务吗？').then(() => {
                // 这里应该调用关闭任务的API
                // 示例: closeWorkOrderTask(row.workOrderTaskId)
                this.$message.success(`已关闭任务: ${row.taskName}`);
                this.getList(); // 刷新数据
            }).catch(() => {});
        } else if (action === 'complete') {
            // 完成任务操作
            this.$modal.confirm('确认要完成此工序任务吗？').then(() => {
                // 这里应该调用完成任务的API
                // 示例: completeWorkOrderTask(row.workOrderTaskId)
                this.$message.success(`已完成任务: ${row.taskName}`);
                this.getList(); // 刷新数据
            }).catch(() => {});
        } else if (action === 'restart') {
            // 重启任务操作
            this.$modal.confirm('确认要重启此工序任务吗？').then(() => {
                restartWorkOrderTask(row.workOrderTaskId).then(response => {
                    if (response.code === 200) {
                        this.$modal.msgSuccess("任务重启成功");
                        this.getList(); // 刷新数据
                    } else {
                        this.$modal.msgError(response.msg || "任务重启失败");
                    }
                }).catch(error => {
                    console.error("重启任务失败:", error);
                    this.$modal.msgError("操作失败，请稍后重试");
                });
            }).catch(() => {});
        }
    },
    /** 开工任务 */
    startTask(row) {
      const taskId = row.workOrderTaskId;
      if (!taskId) {
        this.$modal.msgError("任务ID不能为空");
        return;
      }
      
      this.$modal.confirm('确认要开工此工序任务吗？').then(() => {
        // 使用导入的API方法或者使用通用请求方法
        startWorkOrderTask(taskId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("任务开工成功");
            this.getList(); // 刷新数据
          } else {
            this.$modal.msgError(response.msg || "任务开工失败");
          }
        }).catch(error => {
          console.error("开工任务失败:", error);
          this.$modal.msgError("操作失败，请稍后重试");
        });
      }).catch(() => {});
    },
    /** 处理报工 */
    handleReport(row) {
      // 跳转到报工页面，并传递任务信息
      this.$router.push({
        path: '/sc/Signning',
        query: {
          taskId: row.id,
          orderNo: row.orderNo,
          processName: row.processName
        }
      });
    },
    /** 查看任务详情 */
    handleTaskDetail(row) {
      // 跳转到工序任务详情页面
      this.$router.push({
        path: `/sc/task/detail/${row.workOrderTaskId}`,
        query: {
          taskCode: row.taskCode,
          taskName: row.taskName
        }
      });
    },
    /** 格式化日期时间 */
    formatDate(cellValue) {
      return formatDate(cellValue);
    }
  }
};
</script> 